﻿using System.Diagnostics.Contracts;
using System.IO;

namespace Arachnophile
{
    /// <summary>
    /// Data I/O processing extensions.
    /// </summary>
    public static class DataEx
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static Stream Stream(this byte[] source)
        {
            Contract.Requires(source != null);
            Contract.Ensures(Contract.Result<Stream>() != null);

            return new MemoryStream(source);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static byte[] Data(this Stream stream)
        {
            Contract.Requires(stream != null);
            Contract.Ensures(Contract.Result<byte[]>() != null);

            var buffer = new byte[16 * 1024];
            using (var ms = new MemoryStream())
            {
                var read = 0;
                while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                    ms.Write(buffer, 0, read);
                return ms.ToArray();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="data"></param>
        /// <param name="path"></param>
        public static void Save(this byte[] data, string path)
        {
            Contract.Requires(data != null);
            Contract.Requires(path != null);

            File.WriteAllBytes(path, data);
        }
    }
}
